---
title: Using GraphQL variables in Apollo Kotlin
---

GraphQL supports passing argument values to your operations with [variables](https://graphql.org/graphql-js/passing-arguments/). This enables you to write a single query that you can reuse with multiple variable values (this is a [recommended best practice](/react/data/operation-best-practices/#use-variables-to-provide-graphql-arguments)).

In GraphQL, non-nullable variables are required, and nullable variables are always optional. Apollo Kotlin uses its own [`Optional`](https://apollographql.github.io/apollo-kotlin/kdoc/apollo-api/com.apollographql.apollo.api/-optional/index.html) type to distinguish between present (but maybe nullable) and absent types.

Consider the following GraphQL query with two nullable variables:

```graphql
query GetTodos($first: Int, $offset: Int) {
  todos(first: $first, offset: $offset) {
    id
    text
  }
}
```

Apollo Kotlin generates the following Kotlin code for this query:

```kotlin
class GetTodosQuery(
    val first: Optional<Int?> = Optional.Absent,
    val offset: Optional<Int?> = Optional.Absent
)
```

You can then selectively provide or omit variable values like so:

```kotlin
// Omit values for both variables
val query = GetTodosQuery(Optional.Absent, Optional.Absent)
// Provide null for both variables
val query = GetTodosQuery(Optional.Present(null), Optional.Present(null))
// Send explicit values for both variables
val query = GetTodosQuery(Optional.Present(100), Optional.Present(0))
```

## Using input builders

For both operations and input objects, having to wrap values in an [`Optional`](https://apollographql.github.io/apollo-kotlin/kdoc/apollo-api/com.apollographql.apollo.api/-optional/index.html) wrapper can be cumbersome.

For those cases, use `generateInputBuilders`:

```kotlin
apollo {
  service("service") {
    // ...
    generateInputBuilders.set(true)
  }
}
```

If you do, in the case of the `GetTodos` query shown above, Apollo Kotlin now generates a `Builder` for each operation:

```kotlin
// Omit values for both variables
val query = GetTodosQuery.Builder()
               .build()
// Provide null for both variables
val query = GetTodosQuery.Builder()
               .first(null)
               .offset(null)
               .build()
// Send explicit values for both variables
val query = GetTodosQuery.Builder()
               .first(100)
               .offset(0)
               .build()
```

